<?php
/**
 * @var \common\widgets\cover_upload\CoverUpload $widget
 * @var \yii\web\View $this
 */
use yii\helpers\Html;

$widgetId = "w-cu-".$widget->id;
$uploadUrl = $widget->uploadUrl;
?>

<div id="<?=$widgetId ?>">
    <img src="<?=$widget->showUrl ?>" alt="" width="<?=$widget->coverWidth ?>" class="img img-responsive cover-show">
    <input type="file" class="hidden">
    <?=Html::hiddenInput($widget->name, $widget->coverUrl, $widget->options); ?>
</div>

<?php
$js = <<<JS
var widgetId = '{$widgetId}'
var uploadUrl = '{$uploadUrl}'
$('#'+widgetId).find('img.cover-show').click(function () {
    $('#'+widgetId).find('input[type="file"]').trigger('click')
})
$('#'+widgetId).find('input[type="file"]').on('change', function(e) {
    var formData = new FormData
    var coverObj = this.files[0]
    var file = e.target.files[0];
    if (file) {
        var size = file.size; // 文件大小（字节）
        var kb = size / 1024;
        var mb = kb / 1024;
        // console.log('文件大小: ' + mb.toFixed(2) + ' MB');
        var _mb = Math.floor(mb)
        if ( _mb < 2 ) {
            formData.append('file', coverObj)
            $.ajax({
                async: false,
                url: uploadUrl,
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                dataType: 'json',
                success: function (json) {
                    if (json.code === 200) {
                        $('#'+widgetId).find('img.cover-show').attr('src', json.url);
                        $('#'+widgetId).find('input.cover-upload-input').val(json.url);
                    }
                }
            });
        } else {
            alert('文件不能超过2MB，大小: ' + mb.toFixed(2) + ' MB');
        }
    }
});
JS;
$this->registerJs($js);
